import { useLocation } from 'react-router-dom';
import { useMemo } from "react"
//这个hook用于操作本地存储
type Imethods = {
    set: (value:any) => void
    rm: () => void
    // nickname?:string
}
// 重新声明全局Window索引签名
declare global{
    interface Window{
        [k:string]:any
    }
}
//key 存储到本地存储的key
//value 存储到本地的值
type Istorage = (key: string, storageType?: string,nickname?:string) => [any, Imethods]
const useStorage: Istorage = (key: string, storageType: any = "localStorage",nickname?:string) => {
    let location=useLocation()
    // 使用useMemo从本地获取结果
    let localVal = useMemo<string | null>(() => {
        let valueRes: string | null;
        try {
            valueRes = window[storageType].getItem(key)
            valueRes = valueRes ? JSON.parse(valueRes!) : null
            return valueRes
        } catch (e: any) {
            console.log(e.toString())
            return null
        }
    }, [location])
    let methodObj: Imethods = {
        // 设置缓存
        set: (value: any) => {
            let valueJson;
            try {
                valueJson = JSON.stringify(value!)
                window[storageType].setItem(key, valueJson!)
            } catch (e: any) {
                console.log(e.toString())
            }
        },
        // 移除缓存
        rm: () => {
            window[storageType].removeItem(key)
        }
    }
    return [localVal,methodObj]
}

export default useStorage